<?php
/**
 * Full Page Cache SleekPHP Plug-in
 * Checks if the current URL has a cached copy if so loads that and dies.
 * Clears all cache on $_POST
 *
 * @subpackage Plugins
 */
# Events::bind('BeforeRun', 'SPFullPageCache');
# Events::bind('BeforeOutput', 'SPFullPageCacheWrite');

/**
 * Loads potential cached copy of current URL, clears all cache on $_POST
 */
function SPFullPageCache () {
	$currURL	= currPageURL();
	$currStyle	= SleekPHP::currentStyle();
	$currSite	= SleekPHP::site()->getSite();
	$cachePath	= DOCROOT . 'Sites/SleekBase/Plugins/FullPageCache/Cache/';
	$urlHash	= md5($currSite . $currURL . $currStyle);

	# Create cache dir if it doesn't exist
	if (!is_dir($cachePath)) {
		if (!mkdir($cachePath)) {
			throw new Exception('Unable to create cache dir in ' . WEBROOT . 'Sites/SleekBase/Plugins/FullPageCache/Cache/ please create it manually and make sure it is writeable.');
		}
	}

	# Clear all cache on $_POST
	if (count($_POST)) {
		Logger::log('Clearing cache', __FUNCTION__);

		foreach (glob($cachePath . '*') as $file) {
			unlink($file);
		}

		return;
	}

	# If there's a cached copy use that
	if (file_exists($cachePath . $urlHash)) {
		$cachedPage = file_get_contents($cachePath . $urlHash);

		Logger::log('Cache exists, loaded in ' . round(Logger::getRunTime(), 3) . ' seconds', __FUNCTION__);

		if (function_exists('SPDebugLogger')) {
			$cachedPage = SPDebugLogger($cachedPage);
		}

		die($cachedPage);
	}

	Logger::log('No cache exists, will be created on BeforeOutput', __FUNCTION__);
}

/**
 * Writes current page to cache
 */
function SPFullPageCacheWrite ($output) {
	$currURL	= currPageURL();
	$currStyle	= conf('general.default_style');
	$currSite	= SleekPHP::site()->getSite();
	$cachePath	= DOCROOT . 'Sites/SleekBase/Plugins/FullPageCache/Cache/';
	$urlHash	= md5($currSite . $currURL . $currStyle);

	Logger::log('Writing cache', __FUNCTION__);

	file_put_contents($cachePath . $urlHash, $output);
}
